package futrue;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author lyx
 * @Date 2021/6/26 15:40
 */
public class test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

      /*
        // 异步: 就是在等待 get 方法的中间, 还可以输出main线程的 abc !!!
        // 运行异步 runAsync
        CompletableFuture<Void> completableFuture =CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" runAsync ====> Void");
        });
        //main线程输出 abc
        System.out.println("abc");
        //获取runAsync()执行结果
        completableFuture.get();
        */


        //有返回值
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
            System.out.println("这里是:"+Thread.currentThread().getName()+"supplyAsync ===> Integer");
            //int i = 10/0;
            return 1024;
        });


        System.out.println(
                completableFuture.whenComplete(  //当完成异步方法
                (t, f) -> {
                    System.out.println("t ====>" + t);//正常,返回1024给t
                    System.out.println("f ====>" + f);//错误,返回错误信息给f
                }
        ).exceptionally(  //获取错误的返回结果
                (e) -> {
                    System.out.println("错误信息: "+e.getMessage());
                    return null;
                }
                
        ).get());


    }
}
